(function ($) {
    $.fn.webexcel.plus.tool = function (target) {
        var state = $.data(target, "webexcel"), opts = state.options;
        //判断是否是需要避开的标签符号
        opts.judgePunctuationMarks = function (value) {
            var arr = [".", ",", ";", "?", "!", ":", "\"", "，", "。", "？", "！", "；", "：", "、"];
            for (var i = 0; i < arr.length; i++) {
                if (value === arr[i]) {
                    return true;
                }
            }
            return false;
        };
        //处理需要做换行显示的文字内容
        opts.handlerCellText = function (context, cell) {
            var textArr = (cell.text + '').split('\n');//处理换行符
            //由于改变canvas 的高度会导致绘制的纹理被清空，所以，不预先绘制，先放入到一个数组当中
            var arr = [];
            for (var index = 0; index < textArr.length; index++) {
                var text = textArr[index];
                var lineWidth = 0; //当前行的绘制的宽度
                var lastTextIndex = 0; //已经绘制上canvas最后的一个字符的下标
                for (var i = 0; i < text.length; i++) {
                    //获取当前的截取的字符串的宽度
                    lineWidth = context.measureText(text.substr(lastTextIndex, (i + 1) - lastTextIndex)).width;
                    if (lineWidth > cell.w - cell.padding * 2) {
                        //判断最后一位是否是标点符号
                        if (opts.judgePunctuationMarks(text[i - 1])) {
                            arr.push(text.substr(lastTextIndex, i - lastTextIndex));
                            lastTextIndex = i;
                        } else {
                            arr.push(text.substr(lastTextIndex, i - lastTextIndex - 1));
                            lastTextIndex = i - 1;
                        }
                    }
                    //将最后多余的一部分添加到数组
                    if (i === text.length - 1) {
                        arr.push(text.substr(lastTextIndex, i - lastTextIndex + 1));
                    }
                }
            }
            return arr;
        };
        //获取数据
        opts.getData = function () {
            return opts.data;
        };
        //获取压缩数据
        opts.getCompressData = function () {
            var _data = $.extend(true, {}, opts.data);//复制数据
            var maxRow = 0, maxCol = 0;
            for (var key in _data.contentData) {
                var cell = _data.contentData[key];
                if (cell.text ||
                    opts.cellDefault.bgColor != cell.bgColor ||
                    opts.cellDefault.textColor != cell.textColor ||
                    opts.cellDefault.border != cell.border) {
                    //如果是默认单元格并且没有数据,则不要
                    maxRow = maxRow > cell.endRow ? maxRow : cell.endRow;
                    maxCol = maxCol > cell.endCol ? maxCol : cell.endCol;
                }
            }
            var indexRowData = {}, indexColData = {}, contentData = {};
            for (var row = 0; row <= maxRow; row++) {
                var indexColId = "indexCol_r" + row + "_c0";
                indexColData[indexColId] = _data.indexColData[indexColId];
                for (var col = 0; col <= maxCol; col++) {
                    if (row == 0) {
                        var indexRowId = "indexRow_r0_c" + col;
                        indexRowData[indexRowId] = _data.indexRowData[indexRowId];
                    }
                    var contentId = "content_r" + row + "_c" + col;
                    contentData[contentId] = _data.contentData[contentId];
                }
            }
            _data.indexRowData = indexRowData;
            _data.indexColData = indexColData;
            _data.contentData = contentData;
            return _data;
        };
        //转换页面逻辑数据为正常的二维数组
        opts.convertArrayData = function (data) {
            var contentData = [];
            for (var key in data) {
                var cell = data[key];
                if (!contentData[cell.beginRow]) {
                    contentData[cell.beginRow] = [];
                }
                contentData[cell.beginRow][cell.beginCol] = cell;
            }
            return contentData;
        };
        //导出excel
        opts.doExportExcel = function (fileName) {
            fileName = fileName ? fileName : 'report';
            var type = "xls";
            var application = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            if (type == "xlsx") {
                application = "application/vnd.ms-excel";
            }
            var excelData = opts.convertArrayData(opts.data.contentData);
            var excel = '<table>';
            // 设置数据
            for (var i = 0; i < excelData.length; i++) {
                var row = '<tr>';
                for (var index = 0; index < excelData[i].length; index++) {
                    var cell = excelData[i][index];
                    if (cell.showCell) {
                        var value = cell.text === '.' ? '' : cell.text;
                        if (cell.bold) {//加粗
                            value = '<b>' + value + '</b>';
                        }
                        var style = 'text-align: left;';
                        if (cell.hAlign == 2) {//水平居中
                            style = 'text-align: center;';
                        } else if (cell.hAlign == 3) {//水平居右
                            style = 'text-align: right;';
                        }
                        if (cell.vAlign == 1) {//垂直居上
                            style += 'vertical-align: top;';
                        } else if (cell.vAlign == 2) {//垂直居中
                            style += 'vertical-align: middle;';
                        } else {//垂直居下
                            style += 'vertical-align: bottom;';
                        }
                        //设置单元格边框
                        var borderSize = Math.ceil(cell.borderSize / 2);
                        if (cell.borderLeft) {
                            style += 'border-left: ' + borderSize + 'px solid ' + cell.borderColor + ';';
                        }
                        if (cell.borderTop) {
                            style += 'border-top: ' + borderSize + 'px solid ' + cell.borderColor + ';';
                        }
                        if (cell.borderRight) {
                            style += 'border-right: ' + borderSize + 'px solid ' + cell.borderColor + ';';
                        }
                        if (cell.borderBottom) {
                            style += 'border-bottom: ' + borderSize + 'px solid ' + cell.borderColor + ';';
                        }
                        //设置单元格背景颜色
                        style += 'background-color: ' + cell.bgColor + ';';
                        //设置单元格文字颜色
                        style += 'color: ' + cell.textColor + ';';
                        //设置单元格宽高
                        style += 'width: ' + cell.w + ';height: ' + cell.h + ';';
                        //设置合并单元格
                        var rowspan = cell.endRow - cell.beginRow + 1;
                        var colspan = cell.endCol - cell.beginCol + 1;
                        row += '<td style="' + style + '" rowspan="' + rowspan + '" colspan="' + colspan + '">' + value + '</td>';
                    }
                }
                excel += row + '</tr>';
            }
            excel += '</table>';
            var xmlns = 'xmlns:o=\'urn:schemas-microsoft-com:office:office\' ';
            xmlns += 'xmlns:x=\'urn:schemas-microsoft-com:office:excel\' ';
            xmlns += 'xmlns=\'http://www.w3.org/TR/REC-html40\' ';
            var excelFile = '<html ' + xmlns + '>';
            excelFile += '<meta http-equiv="content-type" content="' + application + '; charset=UTF-8">';
            excelFile += '<head>';
            excelFile += '<!--[if gte mso 9]>';
            excelFile += '<xml>';
            excelFile += '<x:ExcelWorkbook>';
            excelFile += '<x:ExcelWorksheets>';
            excelFile += '<x:ExcelWorksheet>';
            excelFile += '<x:Name>';
            excelFile += 'Sheet1';
            excelFile += '</x:Name>';
            excelFile += '<x:WorksheetOptions>';
            excelFile += '<x:DisplayGridlines/>';
            excelFile += '</x:WorksheetOptions>';
            excelFile += '</x:ExcelWorksheet>';
            excelFile += '</x:ExcelWorksheets>';
            excelFile += '</x:ExcelWorkbook>';
            excelFile += '</xml>';
            excelFile += '<![endif]-->';
            excelFile += '</head>';
            excelFile += '<body>';
            excelFile += excel;
            excelFile += '</body>';
            excelFile += '</html>';
            var uri = 'data:' + application + ';charset=utf-8,' + encodeURIComponent(excelFile);
            var link = document.createElement('a');
            link.href = uri;
            $(link).css("visibility", "hidden");
            $(link).attr("download", fileName + '.' + type);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        };
        //画测试框，相对于容器坐标
        opts.drawTestBox = function (dot, dot2) {
            opts.testBox.css({
                left: dot.x,
                top: dot.y
            }).show();
            if (dot2) {
                setTimeout(function () {
                    opts.testBox.css({
                        left: dot2.x,
                        top: dot2.y
                    }).show();
                }, 1000);
            }
        };
        //两个点坐标计算，calculate=1.加法；calculate=0.减法
        opts.dotCalculate = function (dot1, dot2, calculate) {
            if (calculate == 1) {
                dot1.x = dot1.x + dot2.x;
                dot1.y = dot1.y + dot2.y;
            } else {
                dot1.x = dot1.x - dot2.x;
                dot1.y = dot1.y - dot2.y;
            }
            return dot1;
        };
        //根据窗口坐标获取容器的坐标
        opts.getDotByContainer = function (dot) {
            dot.x = dot.x - opts.containerDot.x;
            dot.y = dot.y - opts.containerDot.y;
            return dot;
        };
        // 获取像素比
        opts.getPixelRatio = function (context) {
            var backingStore = context.backingStorePixelRatio ||
                context.webkitBackingStorePixelRatio ||
                context.mozBackingStorePixelRatio ||
                context.msBackingStorePixelRatio ||
                context.oBackingStorePixelRatio ||
                context.backingStorePixelRatio || 1;
            return (window.devicePixelRatio || 1) / backingStore;
        };
        //用于将Excel表格中列号字母转成列索引，从0对应A开始
        opts.columnToIndex = function (column) {
            var index = 0;
            if (/^[A-Z]/.test(column)) {
                var chars = column.toUpperCase().split('');
                for (var i = 0; i < chars.length; i++) {
                    index += (chars[i].charCodeAt() - 'A'.charCodeAt() + 1) * Math.pow(26, chars.length - i - 1) - 1;
                }
            }
            return index;
        };
        //用于将excel表格中列索引转成列号字母，从A对应0开始
        opts.indexToColumn = function (index) {
            index++;
            var column = "";
            if (index > 0) {
                index--;
                do {
                    if (column) {
                        index--;
                    }
                    column = String.fromCharCode((index % 26 + 'A'.charCodeAt())) + column;
                    index = ((index - index % 26) / 26);
                } while (index > 0);
            }
            return column;
        };
    };

})(jQuery);